import { useState, useEffect, useRef, RefObject } from 'react';
import { Modal, Form, Input, Select, DatePicker, message, FormInstance } from 'antd';
import moment, { Moment } from 'moment'
import TimePicker from '@src/components/timePicker'
import { CaseSchema } from '@src/components/schema/caseSchema';
import { VideoCourtSchema } from '@src/components/schema/videoCourt';
import { getCaseListRequsest, getRoomListRequest, getRecorderRequest } from './ajax'
import { awaitWrap } from '@src/assets/js/tool';
import { RoomSchema } from '@src/components/schema/room';
import _ from 'lodash';
import RoomSelector from '../../components/roomSelector/index'
import { useSelector } from 'react-redux';
import { INIT_BASIC_STATE } from '@src/redux/reducers/basic';

const { Item } = Form
const { Option } = Select
const { TextArea } = Input

async function initRecorder (setList: (v: Array<{ name: string, accountid: string }>) => void) {
  const [e, d] = await awaitWrap(getRecorderRequest())
  if (e === null && d !== null) {
    setList(d)
  }
}

// 获取禁用的小时数
function getDisabledHour () {
  const rs = []
  let i = 0
  while (i <= 24) {
    if (i < 8 || i > 23) {
      rs.push(i)
    }
    i++
  }
  return rs
}

// 获取不可选的分钟数
function getDisabledMinute () {
  const rs = []
  let i = 0
  while (i < 60) {
    if (i % 15 !== 0) {
      rs.push(i)
    }
    i++
  }
  return rs
}

  // 获取禁用日期
function getDisabledDate (c: Moment) {
  const today = moment(moment().format('YYYY-MM-DD'))
  return c < today
}

function onFinish(d: { [k: string]: any }, onChange: (v: { [k: string]: any }) => void) {
  let { date, begintime, endtime } = d
  date = date.format('YYYY-MM-DD')
  d.begin_datetime = moment(`${date} ${begintime.format('HH:mm')}`)
  d.end_datetime = moment(`${date} ${endtime.format('HH:mm')}`)
  if (typeof d.recorder === 'string') {
    try {
      const o = JSON.parse(d.recorder) as { id: string, name: string, accountid: string }
      d.recorder = o.name
      d.recorderid = o.accountid
    } catch (e) {
      console.error(e)
    }
  }
  delete d.date
  delete d.begintime
  delete d.endtime
  onChange(d)
}

async function getCaseList (v: string, id: string, setCaseList: (v: CaseSchema[]) => void) {
  const [e, d] = await awaitWrap(getCaseListRequsest(v, id))
  if (e === null && d !== null) {
    setCaseList(d)
  }
}

const dGetCaseList = _.debounce(getCaseList, 400)

async function initRoomList (setRoomList: (v: RoomSchema[]) => void) {
  const [e, d] = await awaitWrap(getRoomListRequest())
  if (e === null && d !== null) {
    setRoomList(d)
  }
}

function selectCase (v: string, list: CaseSchema[], formRef: RefObject<FormInstance>) {
  let c = null
  for (let i = 0; i < list.length; i++) {
    if (list[i].caseno_desc === v) {
      c = list[i]
      break
    }
  }
  if (c) {
    formRef.current?.setFieldsValue({
      caseid: c.id
    })
  }
}

// 格式化数据
function initData (o: { [k: string]: any }, formRef: RefObject<FormInstance>) {
  if (!o) {
    return undefined
  }
  const { caseid, caseno_desc: d, begin_datetime: b, end_datetime: e, remark, use, id, hearingroomid, type } = o
  const dateStr = b ? moment(b * 1000).format('YYYY-MM-DD') : ''
  const data: {[k: string]: any} = {
    id,
    caseid: caseid || '',
    caseno_desc: d || undefined,
    hearingroomid: hearingroomid,
    date: dateStr ? moment(dateStr) : undefined,
    begintime: b && dateStr ? moment(`${dateStr} ${moment(b * 1000).format('HH:mm')}`) : undefined,
    endtime: e && dateStr ? moment(`${dateStr} ${moment(e * 1000).format('HH:mm')}`) : undefined,
    remark: remark || undefined,
    use: use || undefined,
    type: type || undefined
  }
  if (o.recorder && o.recorderid) {
    data.recorder = JSON.stringify({ accountid: o.recorderid, name: o.recorder })
  }
  if (!formRef.current) {
    setTimeout(() => {
      initData(o, formRef)
    }, 100)
  } else {
    formRef.current.setFieldsValue(data)
  }
}

interface Props {
  visible: boolean
  data: VideoCourtSchema | null
  hide: () => void
  onChange: (v: { [k: string]: any }) => void
}

function Main ({ visible, data, hide, onChange }: Props) {
  const [caseList, setCaseList] = useState<CaseSchema[]>([])
  const [date, setDate] = useState<Moment | null>(null)
  const formRef = useRef<FormInstance>(null)
  const [recorders, setRecorders] = useState<Array<{ name: string, accountid: string }>>([])
  const id = data ? data.id : undefined
  const { userInfo } = useSelector((state: { basic: INIT_BASIC_STATE }) => {
    return {
      userInfo: state.basic.userInfo
    }
  })
  useEffect(() => {
    initRecorder(setRecorders)
  }, [])
  useEffect(() => {
    if (visible) {
      if (data) {
        setDate(moment(data.begin_datetime * 1000))
        initData(data, formRef)
        getCaseList(data.caseno_desc, userInfo.id, setCaseList)
      }
    } else {
      setDate(null)
    }
  }, [data, visible])
  return (
    <Modal
      title={id ? '修改视频庭审' : '新增视频庭审'}
      visible={visible}
      onOk={() => formRef.current?.submit()}
      onCancel={() => hide()}
      width='620px'
      destroyOnClose
      maskClosable={false}
    >
      <Form ref={formRef} labelCol={{ flex: '88px' }} onFinish={d => onFinish(d, onChange)}>
        <Item name='id' noStyle><span /></Item>
        <Item noStyle name='caseid'><span /></Item>
        <Item label='案号' name='caseno_desc' rules={[{ required: true, message: '案号不能为空' }]}>
          <Select showSearch placeholder='选择案号' onSearch={v => dGetCaseList(v, userInfo.id, setCaseList)} onChange={v => selectCase(v, caseList, formRef)}>
            {caseList.map(li => <Option key={li.id} value={li.caseno_desc}>{li.caseno_desc}</Option>)}
          </Select>
        </Item>
        <Item label='开庭日期' name='date' rules={[{ required: true, message: '开庭不能为空' }]}>
          <DatePicker style={{ width: '100%' }} disabledDate={c => getDisabledDate(c)} onChange={v => setDate(v)} />
        </Item>
        <Item label='虚拟庭室' name='hearingroomid' rules={[{ required: true, message: '虚拟庭室不能为空' }]}>
          <RoomSelector date={date} visible={visible} />
        </Item>
        <Item label='用途' name='use' rules={[{ required: true, message: '用途不能为空' }]}>
          <Select placeholder='请选择用途'>
            <Option value='开庭'>开庭</Option>
            <Option value='合议'>合议</Option>
            <Option value='调解'>调解</Option>
          </Select>
        </Item>
        <Item label='类型' name='type' rules={[{ required: true, message: '类型不能为空' }]}>
          <Select placeholder='请选择类型'>
            <Option value='测试'>测试</Option>
            <Option value='正式'>正式</Option>
          </Select>
        </Item>
        <Item label='开始时间' name='begintime' rules={[{ required: true, message: '开始时间不能为空' }]}>
          <TimePicker disabledHours={() => getDisabledHour()} disabledMinutes={() => getDisabledMinute()} />
        </Item>
        <Item label='结束时间' name='endtime' rules={[{ required: true, message: '结束时间不能为空' }]}>
          <TimePicker disabledHours={() => getDisabledHour()} disabledMinutes={() => getDisabledMinute()} />
        </Item>
        <Item label='速录员' name='recorder'>
          <Select placeholder='请选择' allowClear>
            {recorders.map((li, i) => {
              return <Option key={i} value={JSON.stringify({ accountid: li.accountid, name: li.name })}>{li.name}</Option>
            })}
          </Select>
        </Item>
        <Item label='备注' name='remark'>
          <TextArea rows={3} placeholder='请输入备注' />
        </Item>
      </Form>
    </Modal>
  )
}

export default Main
